<script setup>

import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {ref} from "vue";
import {deleteGoods, goodsList, goodsTypeList, insertGoods, updateGoods} from "@/api/goods";
import {useUserInfoStore} from "@/stores/userInfo";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteUser} from "@/api/user";

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数
const goodsListData = ref([])
const form = ref(null)
const dialogFormVisible = ref(false)
const titleName = ref('')
const userInfoStore = useUserInfoStore();
const goodsTypeListData = ref([])
const formLabelWidth = '140px'
const imageUrl = ref('')
// 商品添加、编辑表单数据模型
const formData = ref({
  name: '',
  price: '',
  pubdate:'',
  typeId: '',
  intro:'',
  picture:'',
  flag:''
})
const formParams = ref({
  name: '',
  pubdate: '',
  typeId: '',
  flag: ''
})

// 当每页条数发生了变化，会调用
const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}
// 当当前页面发生变化，会调用
const handleCurrentChange = (val) => {
  pageNum.value = val
  getGoodsList()
}
const getGoodsList = ()=>{
  const params = {
    pageNum : pageNum.value,
    pageSize: pageSize.value,
    ...formParams.value,
  }
  goodsList(params).then(res=>{
    if (res.status) {
      goodsListData.value = res.data.records
      total.value = res.data.total
    }
  })
}
const getGoodsTypeList = ( )=>{
  goodsTypeList().then(res =>{
    if (res.status) {
      goodsTypeListData.value = res.data
    }
  })
}
getGoodsTypeList()
getGoodsList()
const resetParams = ()  =>{
  formParams.value = {
    name: '',
    pubdate: '',
    typeId: '',
    flag: ''
  }
  getGoodsList()
}
// 添加
const addGoods= ()  =>{
  form.value.validate(valid=>{
    if (valid) {
      insertGoods(formData.value).then(res=>{
        if (res.status) {
          getGoodsList()
          dialogFormVisible.value = false
          ElMessage.success("添加成功")
        }
      })
    }
  })
}
const editGoods = () =>{
  form.value.validate(valid=>{
    if (valid) {
      updateGoods(formData.value).then(res=>{
        if (res.status) {
          getGoodsList()
          dialogFormVisible.value = false
          ElMessage.success("修改成功")
        }
      })
    }
  })
}
const  showAddDialog = (title)=>{
  // 清空表单
  resetFormData()
  titleName.value = title
  dialogFormVisible.value = true
}
// 上传图片的回调
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = response.url
  formData.value.picture = response.url
}
// 清空表单
const resetFormData = ()=>{
  formData.value = {
    name: '',
    price: '',
    pubdate:'',
    typeId: '',
    intro:'',
    picture:'',
    flag:''
  }
}
// 打开编辑抽屉
const showEditDialog = (row,title)=>{
  console.log(row)
  formData.value = {
    id: row.id,
    name: row.name,
    // price: row.price,
    pubdate:row.pubdate,
    typeId: row.typeId,
    intro:row.intro,
  }
  // formData.value.flag = row.flag? 'true':'false'
  imageUrl.value = row.picture
  titleName.value = title
  dialogFormVisible.value = true
}
// 删除
const deleteById = (id)=>{
  ElMessageBox.confirm(
      '确认删除吗，删除后不可恢复?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteGoods(id).then(res=>{
          if (res.status) {
            getGoodsList()
            ElMessage.success("删除成功")
          }
        })
      })
      .catch(() => {})
}
// 表单校验
const rules = {
  name: [
    {required: true, message: '请输入食品名', trigger: 'blur'},
    {min: 4, max: 16, message: '长度为4-16位', trigger: 'blur'},
  ],
  intro: [
    {required: true, message: '请输入简介', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'},
  ],
  pubdate: [
    {required: true, message: '请选择时间', trigger: 'change'},
  ],
  typeId: [
    {required: true, message: '请选择时间', trigger: 'change'},
  ],
  picture: [
    {required: true, message: '请上传图片', trigger: 'change'},
  ],
  flag:[
    {required: true, message: '请选择状态', trigger: 'change'},
  ]
}
const handleSelectionChange = (val) => {
  console.log(val)
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>模块管理</span>
        <div class="extra">
<!--          <el-button type="danger">批量删除</el-button>-->
          <el-button type="primary" @click="showAddDialog('添加食品')">添加食品</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline  :model="formParams">
      <el-form-item label="食品名称：">
        <el-input v-model="formParams.name" placeholder="请输入食品名称"></el-input>
      </el-form-item>
      <el-form-item label="时间：">
        <el-date-picker
            v-model="formParams.pubdate"
            type="date"
            placeholder="请选择时间"
            size="default"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="类别：">
        <el-select placeholder="请选择" v-model="formParams.typeId">
          <el-option v-for="type in goodsTypeListData" :label="type.name" :value="type.id" :key="type.id"></el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="状态：">-->
<!--        <el-select placeholder="请选择" v-model="formParams.flag">-->
<!--          <el-option label="上架" value="1"></el-option>-->
<!--          <el-option label="下架" value="0"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="getGoodsList">搜索</el-button>
        <el-button @click="resetParams">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 商品列表 -->
    <el-table :data="goodsListData" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column label="食品名"  prop="name"></el-table-column>
<!--      <el-table-column label="价格" prop="price"></el-table-column>-->
      <el-table-column label="时间" prop="pubdate"></el-table-column>
      <el-table-column label="类别" prop="typeId">
        <template #default="{row}">
          <el-tag>{{goodsTypeListData.filter(item=>item.id===row.typeId)[0].name}}</el-tag>
<!--          <el-tag>{{goodsTypeListData[0].name}}</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column label="简介" prop="intro" show-overflow-tooltip></el-table-column>
      <el-table-column label="图片" prop="picture">
        <template #default="{row}">
          <img :src="row.picture" style="height: 150px">
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" prop="flag">-->
<!--        <template #default="{row}">-->
<!--          <el-tag :type="row.flag?'success':'danger'">{{row.flag?'上架':'下架'}}</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="添加时间" prop="createTime"></el-table-column>-->
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditDialog(row,'编辑食品')"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteById(row.id)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>

  <el-drawer v-model="dialogFormVisible" direction="rtl">
    <template #header>
      <h4>{{titleName}}</h4>
    </template>
    <template #default>
      <el-form ref="form" :model="formData"  label-position="top" :rules="rules">
        <el-form-item label="食品名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="formData.name" autocomplete="off" placeholder="请输入食品名" />
        </el-form-item>
<!--        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">-->
<!--          <el-input v-model="formData.price" autocomplete="off" placeholder="请输入价格" />-->
<!--        </el-form-item>-->
        <el-form-item label="时间：" prop="pubdate" :label-width="formLabelWidth">
          <el-date-picker
              v-model="formData.pubdate"
              type="date"
              placeholder="请选择时间"
              size="default"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="类别：" prop="typeId" :label-width="formLabelWidth">
          <el-select placeholder="请选择" v-model="formData.typeId">
            <el-option v-for="type in goodsTypeListData" :label="type.name" :value="type.id" :key="type.id"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="状态：" prop="flag" :label-width="formLabelWidth">-->
<!--          <el-select placeholder="请选择" v-model="formData.flag" >-->
<!--            <el-option label="上架" value="true"></el-option>-->
<!--            <el-option label="下架" value="false"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="图片" prop="picture">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"

          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth" prop="intro">
          <el-input type="textarea" v-model="formData.intro" autocomplete="off" placeholder="请输入简介" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogFormVisible =false">取消</el-button>
        <el-button type="primary" @click="titleName==='添加食品'?addGoods():editGoods()">确认</el-button>
      </div>
    </template>
  </el-drawer>

</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
